<template>
  <eui-background type="common">
    <eui-nav-bar ref="BcmNavBar" title="部分退款" />
    <view class="footer" :style="{ height: height + 'px' }" v-if="goodsList.length > 0">
      <view
        style="width: 100%; background: #FFE9DA;padding: 15rpx 20rpx 15rpx 15rpx;color:#FF0000;box-sizing: border-box;font-size: 32rpx;line-height: 35rpx;"
        class="flex just-between align-center">
        <view style="flex: 1;">提示：为避免顾客投诉，建议在操作退款前与顾客联系协商一致</view>
        <view
          style="padding:6rpx 10rpx;height: 35rpx;border-radius: 3rpx;border: 1rpx solid #FF0000;text-align: center;line-height: 35rpx;margin-left: 22rpx;"
          @click="openContactCustPop" v-if="!!consigneePhone">
          联系顾客</view>
      </view>
      <view style="height: 65rpx;font-size: 32rpx;line-height: 65rpx;padding: 0 17rpx 0 10rpx;box-sizing: border-box;"
        class="flex align-center just-between">
        <view>请选择需要部分退款的商品</view>
      </view>
      <scroll-view scroll-y="true" class="bg-white"
        style="width: 100%;padding: 10rpx 18rpx;box-sizing: border-box;overflow-y: scroll;">
        <view>
          <view class="goods-item just-between" v-for="(item, index) in goodsList" :key="index">
            <view
              style="width: 40rpx;height: 40rpx;text-align: center;line-height: 40rpx;background-color: #D8D8D8;color: #fff;border-radius: 31rpx;font-size: 32rpx;">
              {{ index + 1 }}
            </view>
            <view style="margin-left: 32rpx;box-sizing: border-box;flex: 1">
              <view>
                <view class="goods-name bold">{{ item.goodsName }}</view>
                <view class="goods-info jus-between">
                  <view style="font-size: 32rpx;color: #626262;">
                    <view>{{ item.goodsCode }}</view>
                    <view>{{ item.goodsBarcode }}</view>
                  </view>
                  <view class="flex" style="flex: 1;justify-content: space-between;margin-left: 100rpx;">
                    <view class="goods-quantity bold"
                      :style="{ 'color': item.partRefundGoodsNum > 1 ? '#E43E00' : '#626262' }">x<text>
                        {{ item.partRefundGoodsNum }}</text>
                    </view>
                    <view class="flex align-center" style="font-size: 32rpx;">
                      <eui-uicons type="minus-filled" size="60"
                        :style="{ 'color': item.applyRefundNum == 0 ? '#D8D8D8 !important' : '#85B6FD !important' }"
                        @click="minusNum(index)"></eui-uicons>
                      <view style="color: #626262;width: 100rpx;" class="text-center">{{ item.applyRefundNum }}</view>
                      <eui-uicons type="plus-filled" size="60"
                        :style="{ 'color': item.applyRefundNum == item.partRefundGoodsNum ? '#D8D8D8 !important' : '#85B6FD !important' }"
                        @click="plusNum(index)"></eui-uicons>
                    </view>
                  </view>
                </view>

              </view>
            </view>
          </view>
          <view style="padding: 22rpx;font-size: 32rpx;">
            <view class="flex just-between bold">
              <view>退款数量</view>
              <view>{{ sumNum() }}件</view>
            </view>
            <view style="margin-top: 10rpx" class="flex just-between bold">
              <view>预计退款金额</view>
              <view style="color: #E43E00;">¥{{ sumPrice() }}</view>
            </view>
            <view style="font-size: 32rpx;color: #A5A5A5;margin-top: 10rpx;">备注：预计退款金额仅供参考，请以实际退款金额为准</view>
          </view>
        </view>
      </scroll-view>
    </view>
    <view class="footer align-center" :style="{ height: height + 'px' }" v-else>
      <view class="m-list-template-image" style="flex: 1;margin-top: 25%;">
        <image :src="_img_blank_order" />
        <view style="color: #9e9e9e;font-size: 32rpx;text-align: center;">无可退商品</view>
      </view>
    </view>
    <view class="bottom" v-if="goodsList.length > 0">
      <eui-button title="下一步" type="max" singleTag="confirm" @buttonClick="buttonClick"
        style="width: 100%;height: 86rpx;line-height: 86rpx;border-radius: 0;margin: 0;padding:0"
        :disabled="sumPrice() == 0 || sumNum() == 0"></eui-button>
    </view>
    <eui-popup ref="popup" background-color="#fff" type="bottom" :mask-click="false">
      <view class="popup-content">
        <view class="popup-title flex just-between">
          <view style="font-weight: bold;">
            选择退款理由
          </view>
          <bcm-close-btn @click="close"></bcm-close-btn>
        </view>
        <scroll-view scroll-y="true"
          style="padding: 8rpx 8rpx 8rpx 30rpx;box-sizing: border-box;height: 70vh;overflow-y: scroll;text-align: left;">
          <radio-group @change="selectItem">
            <view v-for="item in getBcmDictList('orderCancelReasonType')" :key="item.value">
              <radio :value="item.value" :checked="orderCancelReasonType === item.value"
                style="margin-top: 20rpx;line-height: 35rpx">
                {{ item.text }}
              </radio>
            </view>
          </radio-group>
          <textarea v-model="rejectReason" placeholder="请输入原因" v-if="orderCancelReasonType == '999'"></textarea>
        </scroll-view>
        <view class="bottom-1">
          <eui-button type="max" title="提交" style="width: 50%;" singleTag="sure" @buttonClick="buttonClick" />
        </view>
      </view>
    </eui-popup>
    <eui-popup ref="contactCustPopup" type="bottom" :animation="false" background-color="#fff" :mask-click="false">
      <view class="popup-content">
        <view class="popup-title flex just-between">
          <view style="font-weight: bold;">
            联系顾客
          </view>
          <bcm-close-btn @click="closeContactCustPopup"></bcm-close-btn>
        </view>
        <view
          style="padding-left: 30rpx;color: #000;background-color:#fff;box-sizing: border-box;padding-top:24rpx;text-align: left">
          <view>
            <text v-if="!!consigneeName">姓名：{{ consigneeName }}</text><text v-if="!!consigneePhoneLast">(尾号{{
      consigneePhoneLast }})</text>
          </view>
          <view>
            <text v-if="!!consigneePhone">电话：{{ consigneePhone }}</text>
          </view>
          <view class="bottom-1" style="margin: 100rpx 0 50rpx 0;">
            <eui-button type="max" title="拨打电话" style="width: 50%" singleTag="submit" @buttonClick="buttonClick" />
          </view>
        </view>
      </view>
    </eui-popup>
  </eui-background>
</template>
<script setup lang="js">
import { mapState, mapMutations } from 'vuex';
import { ref, computed, onMounted } from 'vue';
import { onLoad } from "@dcloudio/uni-app";
import service from '../../../common/service';
import { bcmRequest, getBcmUrl } from '../../../hooks/bcmServices';
import { getBcmDictList, getBcmDictName, getBcmDictItem, formatPrice } from '../../../hooks/bcmUseUntils';
import BcmCloseBtn from '../components/BcmCloseBtn.vue';
import _img_blank_order from '../../../static/img/status/blank_order.png';

const bcmUrl = getBcmUrl()

const goodsList = ref([])
const orderCancelReasonType = ref('')
const rejectReason = ref('')
const orderId = ref('')
const consigneeName = ref('')
const consigneePhone = ref('')
const consigneePhoneLast = ref('')
const height = ref(0);
const chnlType = ref('');
const orderStatus = ref('');
const contactCustPopup = ref(null)
const popup = ref(null)
const showConfigModal = ref(false)

const plusNum = function (index) {
  if (goodsList.value[index].applyRefundNum < goodsList.value[index].partRefundGoodsNum) {
    goodsList.value[index].applyRefundNum++;
  }
}

const minusNum = function (index) {
  if (goodsList.value[index].applyRefundNum > 0) {
    goodsList.value[index].applyRefundNum--;
  }
}
const selectItem = function (item) {
  orderCancelReasonType.value = item.detail.value;
}

const sumPrice = function () {
  let total = goodsList.value.filter(a => a.applyRefundNum != 0).reduce((accumulator, currentValue) => {
    let num = Number(currentValue.applyRefundNum * currentValue.goodPrice);
    if (!isNaN(num)) {
      return accumulator + num;
    } else {
      return accumulator;
    }
  }, 0);
  // 遍历数组中的每个对象
  return total.toFixed(2);
}

const sumNum = function () {
  return goodsList.value.filter(a => a.applyRefundNum != 0).reduce((accumulator, currentValue) => {
    let num = Number(currentValue.applyRefundNum);
    if (!isNaN(num)) {
      return accumulator + num;
    } else {
      return accumulator;
    }
  }, 0);;
}
const buttonClick = async function (t) {
  const { singleTag } = t;
  let list = goodsList.value.filter(a => a.applyRefundNum != 0);
  switch (singleTag) {
    case 'sure':
      if (!orderCancelReasonType.value) {
        uni.showToast({
          title: '请选择退款理由',
          icon: 'none'
        });
        return;
      }
      if (orderCancelReasonType.value == '999' && !rejectReason.value) {
        uni.showToast({
          title: '请输入退款原因',
          icon: 'none'
        });
        return;
      }
      service.enjoyShowLoading('正在处理...');
      let params = {
        orderId: orderId.value,
        reasonType: orderCancelReasonType.value,
        reasonDesc: orderCancelReasonType.value != '999' ? getBcmDictName('orderCancelReasonType', orderCancelReasonType.value) : rejectReason.value,
        refundGoodsDetailList: list.map(v => {
          return {
            orderGoodsId: v.orderGoodsId,
            refundGoodsNum: v.applyRefundNum,
            prePartReturnInfo: v.prePartReturnInfo
          }
        })
      }

      let response = await bcmRequest(bcmUrl.orderApi, '订单表', 'orderPartRefund', params);
      service.enjoyHideLoading();
      popup.value.close('bottom');
      uni.showToast({
        title: '退款成功',
        icon: 'none'
      });
      if (response?.afsOrderId && (!['2', '1'].includes(response?.syncErpBreakageStatus)) && orderStatus.value == '4' && showConfigModal) {
        uni.navigateTo({
          url: `/pages/BcmViews/PickingOrder/breakage?afsOrderId=` + response?.afsOrderId + '&type=1'
        });
      }else{
        setTimeout(() => {
          uni.navigateBack({
            delta: 1
          });
          uni.$emit('REFRESH_ORDER_DETAIL_DATA');
          uni.$emit('REFRESH_ORDER_SEARCH_DATA')
        }, 1000)
      }
      break;
    case 'confirm':
      if (list.length == 0) {
        uni.showToast({
          title: '请选择需要部分退的商品',
          icon: 'none'
        });
        return;
      }
      popup.value.open('bottom');
      break;
    case 'submit':
      // plus.device.dial(consigneePhone, true);
      uni.makePhoneCall({
        phoneNumber: consigneePhone // 电话号码
      });
      break;
  }
}

const close = function () {
  popup.value.close();
  orderCancelReasonType.value = '';
  rejectReason.value = '';
}

const openContactCustPop = function () {
  contactCustPopup.value.open('bottom');
}

const closeContactCustPopup = function () {
  contactCustPopup.value.close();
}

onLoad((option) => {
  let options = service.getStorageSync('partOptions');
  goodsList.value = options.goodsList;
  orderId.value = options.orderId;
  consigneeName.value = options.consigneeName;
  consigneePhone.value = options.consigneePhone;
  consigneePhoneLast.value = options.consigneePhoneLast;
  chnlType.value = options.chnlType;
  orderStatus.value = option.orderStatus;
  showConfigModal.value = option.showModal || false;

})

</script>
<style lang="scss" scoped>
@import "@/static/font/enjoyicon/iconfont.css";
@import "../common/common.css";

uni-checkbox {
  ::v-deep .uni-checkbox-input {
    // width: 22rpx;
    // height: 22rpx;
    transform: scale(.6);
    // margin-right: 17rpx;
  }
}

.footer {
  display: flex;
  flex-direction: column;
  flex: 1;
  background: #f5f7fa;
}

.align-center {
  align-items: center;
}

.bottom {
  height: 86rpx;
}

.bottom-1 {
  display: flex;
  justify-content: center;
  flex: 0 0 auto;
  height: 70rpx;
  padding: $uni-spacing-col-sm * 2 $uni-spacing-row-sm;
  background: $uni-bg-color;
}

//list
.goods-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx;
  border-bottom: 1rpx solid #e1e1e1;
}

.goods-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.goods-name {
  margin-bottom: 2px;
  font-size: 32rpx;
  line-height: 35rpx;
}

.goods-price {
  font-size: 32rpx;
  text-align: right;
}

.goods-quantity {
  color: #626262;
  font-size: 32rpx;
}

.popup-content {
  display: flex;
  flex-direction: column;
  width: 100%;
  padding: 0;
  background-color: #fff;

  .popup-title {
    display: flex;
    align-items: center;
    box-sizing: border-box;
    width: 100%;
    height: 100rpx;
    padding-right: 36rpx;
    padding-left: 30rpx;
    font-size: 33rpx;
    line-height: 100rpx;
    border-bottom: 1px solid #f1f1f1;
  }

  textarea {
    box-sizing: border-box;
    width: 100%;
    height: 80px;
    padding: 5px;
    margin: 5px 0;
    border: 1px solid #ccc;
    border-radius: 5px;
  }
}
</style>
